<template>
  <!-- 区域 -->
  <div>
    <div class="app-page">
      <org-tree
        title="组织机构"
        :tree-data="orgTreeData"
        :mouse-button="false"
        :loading="$loadingPlugin.getOrgTreeData"
        class="content"
        @currentChange="orgChange"
      />
      <goods-tree
        title="商品分类"
        :tree-data="goodsTypeTreeData"
        :loading="$loadingPlugin.getGoodsTypeTreeData"
        :mouse-button="false"
        class="content"
        @currentChange="goodsTypeChange"
      />

      <!-- 列表 -->
      <el-form ref="form" class="formRight" :model="temp" label-width="0px">
        <el-form-item>
          <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button v-permission="2" type="primary" icon="el-icon-plus" @click="setIntegraRouting">积分路由</el-button>
        </el-form-item>
        <!-- 表单 -->
        <lb-table
          ref="lbTable"
          v-el-height-adaptive-table="{ bottomOffset: 10 }"
          border
          class="formTable"
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          pagination
          :total="tableData.total"
          :immediate-fetch="false"
          custom-column
          @fetch="fetchData"
          @expand-change="clickExpand"
        />
      </el-form>

    </div>

    <integra-routing ref="integraRouting" />
    <edit-integra ref="editintegra" />
  </div>
</template>

<script>
  import {
    goodsTypeQueryList,
    floorfeeSelectList, queryGoodsList
  } from '@/api'
  import { queryScoreRules } from '@/api/index'

  import getTreeData from '@/utils/jsonTree'
  import OrgTree from '@/views/components/OrgTree'
  import GoodsTree from '@/views/components/GoodsTypeTree'
  import IntegraRouting from './components/IntegraRouting'
  import EditIntegra from './components/Editintegra'
  import { mapGetters } from 'vuex'
  export default {
    name: 'scoreRuleSetting',
    components: {
      OrgTree,
      GoodsTree,
      IntegraRouting,
      EditIntegra
    },
    data() {
      return {
        expandData: [],
        indexId: 0,
        orgTreeData: [],
        goodsTypeTreeData: [],
        currentOrg: null,
        currentGoodsType: null,
        temp: {},
        csmType1: {
          requiredScore: undefined,
          givenScore: undefined
        },
        csmType2: {
          requiredScore: undefined,
          givenScore: undefined
        },
        csmType4: {
          requiredScore: undefined,
          givenScore: undefined
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              type: 'expand',
              render: (h, { row }) => {
                console.log(this.currentGoodsType.gtCategory)
                return (
                  <div>
                  {this.expandData[row.goodsId] && this.expandData[row.goodsId].length && this.currentGoodsType ? (
                    this.currentGoodsType && this.currentGoodsType.gtCategory === 4
                    ? <div class='expand-data'>
                      <div class='expand-detail'>居民用户:兑换所需积分{this.expandData[row.goodsId][0].requiredScore1}</div>
                      <div class='expand-detail'>非居民用户:兑换所需积分{this.expandData[row.goodsId][0].requiredScore2}</div>
                      <div class='expand-detail'>工业用户:兑换所需积分{this.expandData[row.goodsId][0].requiredScore4}</div>
                    </div> : <div class='expand-data'>
                      <div class='expand-detail'>居民用户:购买赠送积分{this.expandData[row.goodsId][0].givenScore1}</div>
                      <div class='expand-detail'>非居民用户:购买赠送积分{this.expandData[row.goodsId][0].givenScore2}</div>
                      <div class='expand-detail'>工业用户:购买赠送积分{this.expandData[row.goodsId][0].givenScore4}</div>
                    </div>) : <div class='expand-empty'>该商品没有配置积分</div>}
                  </div>
                )
              }
            },
            {
              prop: 'goodsCode',
              label: '商品编码'
            },
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'gtName',
              label: '类型'
            },
            {
              prop: 'unitName',
              width: 50,
              align: 'center',
              label: '单位'
            },
            {
              label: '操作',
              width: 70,
              render: (h, { row, $index }) => {
                return (
                  <el-link v-permission='3' size='mini' underline={false} onClick={() => this.editIntegraHandler(row, $index)}>
                    商品积分
                  </el-link>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getOrgTreeData(), this.getGoodsTypeTreeData()])
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        const res = await queryGoodsList({
          gtId: this.currentGoodsType.gtId,
          orgSNNo: this.currentOrg.orgSNNo,
          currentPage,
          pageSize
        })
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取组织机构数据
      async getOrgTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.orgTreeData = getTreeData(data)
      },
      // 选择组织机构变化
      orgChange(current) {
        this.currentOrg = current
        if (this.currentOrg && this.currentGoodsType && this.$refs.lbTable) this.$refs.lbTable.fetch()
      },
      // 获取树图数据
      async getGoodsTypeTreeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTypeTreeData = getTreeData(data, 'parentId', 'gtId')
      },
      // 商品分类变化
      goodsTypeChange(current) {
        this.currentGoodsType = current
        if (this.currentOrg && this.currentGoodsType && this.$refs.lbTable) this.$refs.lbTable.fetch()
      },
      async setIntegraRouting(row) {
        await this.$refs.integraRouting.open(row)
        this.$refs.lbTable.fetch()
      },
      async editIntegraHandler(row) {
        await this.$refs.editintegra.open(row, this.currentOrg, this.currentGoodsType)
        this.$refs.lbTable.fetch()
      },
      getGoodList() {
        if (this.currentGoodsType == null) {
          return
        }
        if (this.currentOrg == null) {
          this.$message({
            message: '请选择商品分类！',
            type: 'warning'
          })
          return
        }
        const orgId = this.currentOrg.orgId
        const gtId = this.currentGoodsType.gtId
        floorfeeSelectList({
          orgId,
          gtId
        }).then(res => {
          if (res.success) {
            this.tableData.data = res.data.rows
          }
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 展开行
      async clickExpand(row, expandedRows) {
        if (expandedRows.length > 0) {
          const goods = expandedRows.find(item => item.goodsId === row.goodsId)
          if (goods) {
            this.$set(this.expandData, goods.goodsId, [])
            const res = await queryScoreRules({
              goodsId: row.goodsId,
              orgSNNo: this.currentOrg.orgSNNo
            })
            const resData = JSON.parse(res.data.dataList)
            if (resData.length > 0) {
              resData.forEach(item => {
                if (item.csmType === 1) {
                  if (item.givenScore > 0) this.csmType1.givenScore = item.givenScore >> 1
                  if (item.requiredScore > 0) this.csmType1.requiredScore = item.requiredScore >> 1
                } else if (item.csmType === 2) {
                  if (item.givenScore > 0) this.csmType2.givenScore = item.givenScore >> 1
                  if (item.requiredScore > 0) this.csmType2.requiredScore = item.requiredScore >> 1
                } else if (item.csmType === 4) {
                  if (item.givenScore > 0) this.csmType4.givenScore = item.givenScore >> 1
                  if (item.requiredScore > 0) this.csmType4.requiredScore = item.requiredScore >> 1
                }
              })
              this.$set(this.expandData, goods.goodsId, [
                { givenScore1: this.csmType1.givenScore, requiredScore1: this.csmType1.requiredScore,
                  givenScore2: this.csmType2.givenScore, requiredScore2: this.csmType2.requiredScore,
                  givenScore4: this.csmType4.givenScore, requiredScore4: this.csmType4.requiredScore
                }
              ])
            } else {
              console.log(222)
              this.$set(this.expandData, goods.goodsId, [])
            }
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  width: 100%;
  height: calc(100vh - 130px);
  padding: 0;
  .content {
    max-width: 280px;
    padding: 0 10px 0 10px;
    //flex: 1;
  }

  .formRight {
    margin-left: 10px;
    flex: 1;
    overflow-x: auto;
  }
  .formTable {
    width: 100%;
  }
  /deep/.expand-data {
    padding: 20px;
    .expand-detail {
      margin-bottom: 20px;
    }
  }
  /deep/.expand-empty {
    padding: 20px;
  }
}

</style>
